package subcommands

import (
	"fmt"
	"rc/logger"
	"rc/remote"
	"rc/repo"
	"rc/repo/model"
	"strings"

	flags "github.com/jessevdk/go-flags"
	"github.com/urfave/cli"
)

func LoginCli(c *cli.Context) error {

	return loginByUserInfo(c.String("node"), c.String("user"))
}

func Login(args []string) error {
	var (
		err error
		log = logger.GetLogger()
	)

	// opts for login subcommand
	var opts struct {
		Node string `short:"n" long:"node" description:"node name" required:"true"`
		User string `short:"u" long:"user" description:"user name for login"`
	}

	var parser = flags.NewParser(&opts, flags.HelpFlag|flags.PassDoubleDash)
	parser.Command.Name = "login" // set current command name
	_, err = parser.ParseArgs(args)
	if err != nil {
		if err.(*flags.Error).Type == flags.ErrHelp {
			fmt.Println(err.Error())
			return nil
		}
		log.Debug("parser error : %#v\n", err)
		return err
	}
	log.Debug("opts: %v\n", opts)

	// find node
	return loginByUserInfo(opts.Node, opts.User)
}

func loginByUserInfo(nodeName, userName string) error {
	var (
		err error
		n   model.Node
		r   repo.Repo
		re  remote.Remote
		log = logger.GetLogger()
	)

	r = repo.GetRepo()
	if r == nil {
		return fmt.Errorf("may be repo is empty, default repo is : ~/.rc.json")
	}

	n, err = r.GetFirstNode(nodeName, "")
	if err != nil {
		return err
	}
	log.Debug("node: %#v\n", n)

	var userInfo = getFirstUser(n, userName)
	if userInfo.UserName == "" {
		return fmt.Errorf("not found login user info")
	}

	// login by userInfo
	re = remote.New(userInfo.UserName, userInfo.Password, userInfo.KeyPath, n.IPv4, n.Port)
	return re.Login()
}

func getFirstUser(n model.Node, user string) model.UserInfo {
	for _, u := range n.UserInfos {
		if strings.Index(u.UserName, user) >= 0 {
			return u
		}
	}

	return model.UserInfo{}
}
